package com.jolink.omiis.wechat.api.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.joinlink.omiis.commons.persistence.api.IDBProcessor;
import com.joinlink.omiis.commons.persistence.impl.DBProcessor;

public class TemplateMessageBuilder {

	private static Logger logger = LoggerFactory.getLogger(TemplateMessageBuilder.class);

	@SuppressWarnings("unchecked")
	public static <V> String createTemplateMessage(String id, String toUser, String url, V v) {
		TemplateEntry entry = queryTemplate(id);
		JsonObject message = new JsonObject();
		message.addProperty("touser", toUser);
		message.addProperty("template_id", entry.getTemplateId());
		message.addProperty("url", url);
		JsonObject data = new JsonObject();
		Map<String, String> value = null;
		if (v instanceof Map) {
			value = (Map) v;
		}

		for (TemplateEntryItem e : entry.getItems()) {
			String name = e.getName();
			String color = e.getColor();
			JsonObject element = new JsonObject();
			element.addProperty("value", value.get(name));
			element.addProperty("color", color);
			data.add(name, element);
		}
		message.add("data", data);
		logger.info("模板ID：{}，内容：{}。", entry.getTemplateId(), message);
		return message.toString();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static TemplateEntry queryTemplate(String id) {
		String templateId = null;
		String sql = "select id,app_id,name,template_id from wechat_template where id=?";
		IDBProcessor processor = new DBProcessor();
		try {
			List<Map<String, String>> result = processor.query(sql, new String[] { id });
			if (result == null || result.isEmpty()) {
				throw new RuntimeException("模板：" + id + "信息不存在！");
			}
			logger.info("ID：{}，模板信息：{}。", id, result);
			templateId = result.get(0).get("template_id");
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}

		String sql2 = "select id,tid,tag_name,tag_color from wechat_template_data where tid=?";
		TemplateEntry entry = new TemplateEntry();
		entry.setTemplateId(templateId);
		try {
			List<Map<String, String>> result = processor.query(sql2, new String[] { id });
			if (result == null || result.isEmpty()) {
				throw new RuntimeException("模板：" + id + "详细信息不存在！");
			}
			logger.info("ID：{}，模板详细信息：{}。", id, result);
			for (Map<String, String> item : result) {
				entry.addItem(new TemplateEntryItem(item.get("tag_name")));
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return entry;
	}

}

class TemplateEntry {
	private String templateId;

	public TemplateEntry() {
		items = new ArrayList<>();
	}

	/**
	 * @return the templateId
	 */
	public String getTemplateId() {
		return templateId;
	}

	/**
	 * @param templateId
	 *            the templateId to set
	 */
	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}

	private List<TemplateEntryItem> items;

	public void addItem(TemplateEntryItem e) {
		items.add(e);
	}

	/**
	 * @return the items
	 */
	public List<TemplateEntryItem> getItems() {
		return items;
	}
}

class TemplateEntryItem {
	public TemplateEntryItem(String name, String color) {
		this.name = name;
		this.color = color;
	}

	public TemplateEntryItem(String name) {
		this(name, "#173177");
	}

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	private String color;
}
